package cn.wolfcode.luowowo.wensite.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.wensite.web.annotation.RequireLogin;
import cn.wolfcode.luowowo.wensite.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查拦截器
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String cookie = CookieUtil.getCookie(request);
//        UserInfo userInfo = userInfoRedisService.getToken(cookie);
//        if (userInfo == null) {
//            response.sendRedirect("/login.html");
//            return false;
//        }


        UserInfo user = null;
        //获取当前请求方法
        //判断springmvc中,静态资源是不是这个handler
        if (handler instanceof HandlerMethod) {
            HandlerMethod mh = (HandlerMethod) handler;
            //判断当前方法是否贴了自定义注解
            if (mh.hasMethodAnnotation(RequireLogin.class)) {
                //如果有就登录检查
                String cookie = CookieUtil.getCookie(request);
                user = userInfoRedisService.getToken(cookie);
                if (user == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
                request.getSession().setAttribute("userInfo",user);
            }
        }
        //没有就是直接放行
        return true;
    }
}
